<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Example
 *
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array.
 *
 * @package		CodeIgniter
 * @subpackage	Rest Server
 * @category	Controller
 * @author		phuong101899
*/

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH.'/libraries/REST_Controller.php';

class Drink extends REST_Controller
{
    function __construct(){
        parent::__construct();
        $this->load->model('drink/Drink_model');
    }
	function add_post(){
        $user_id = $this->get_user()['id'];
        $data = array(
            'name'  => $this->post('name'),
            'price' => (int)$this->post('price'),
            'user_id' => $user_id,
            'unit'  =>$this->post('unit')
        );
        if($this->post('id')){
            $where = array('id'=>$this->post('id'));
            $flag = $this->Drink_model->edit($data,$where);
        }else{
            $flag = $this->Drink_model->add($data);
        } 
        $this->response(array('status'=>$flag),200);
    }
    function list_get(){
        $user = array('user_id'=>$this->get_user()['id']);
        $data = $this->Drink_model->get_all($user);
        if($data && is_array($data) && count($data)){
            $this->response(array('status'=>TRUE,'data'=>$data));
        }else{
            $this->response(array('status'=>FALSE,'msg'=>'No data'));
        }
    }
    function item_post(){
        $user = array('user_id'=>$this->get_user()['id']);
        $id = array('id' => $this->post('id'));
        $where = array_merge($user,$id);
        $data = $this->Drink_model->get_item($where);
        if($data && is_array($data)){
            $this->response(array('status'=>TRUE,'data'=>$data));
        }else{
            $this->response(array('status'=>FALSE,'msg'=>'No data'));
        }
    }
    function delete_post(){
        $id = $this->post('id');
        $where = array($id);
        if(preg_match('/,/', $id)){
            $where = implode(',', $id); // use delete in array 
        }
        $flag = $this->Drink_model->delete('id',$where);
        $this->response(array('status'=>$flag));
    }
    private function get_user(){
        if(isset($_SESSION['user'])){
            return $_SESSION['user'];
        }  
    }
}